<!-- MySelling.vue - 我的出售（商品管理）-->
<template>
  <div class="my-selling-page">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="header-left">
        <el-icon class="header-icon"><Sell /></el-icon>
        <div>
          <h2 class="header-title">我的出售</h2>
          <p class="header-subtitle">共 {{ products.length }} 件商品在售</p>
        </div>
      </div>
      <div class="header-right">
        <el-button type="info" size="large" @click="viewSalesOrders">
          <el-icon><List /></el-icon>
          查看销售订单
        </el-button>
        <el-button type="primary" size="large" @click="handlePublishNew">
          <el-icon><Plus /></el-icon>
          发布新商品
        </el-button>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton v-for="i in 4" :key="i" :rows="3" animated class="loading-card" />
    </div>

    <!-- 空状态 -->
    <div v-else-if="products.length === 0" class="empty-state">
      <el-empty description="还没有发布商品">
        <el-button type="primary" size="large" @click="handlePublishNew">
          立即发布
        </el-button>
      </el-empty>
    </div>

    <!-- 商品列表 -->
    <div v-else class="products-grid">
      <el-card 
        v-for="product in products" 
        :key="product.productId"
        class="product-card"
        shadow="hover"
      >
        <div class="product-image">
          <el-image :src="getImageUrl(product.coverList)" fit="cover">
            <template #error>
              <div class="image-error">
                <el-icon><PictureFilled /></el-icon>
              </div>
            </template>
          </el-image>
        </div>

        <div class="product-info">
          <h3 class="product-name">{{ product.productName }}</h3>
          <div class="product-meta">
            <el-tag :type="getOldLevelType(product.oldLevel)" size="small">
              {{ getOldLevelText(product.oldLevel) }}
            </el-tag>
            <!-- 商品状态标签 -->
            <el-tag 
              :type="getStatusType(product.status)" 
              size="small"
              :class="['status-tag', { 'sold-tag': product.status === 'sold' }]">
              {{ getStatusText(product.status) }}
            </el-tag>
          </div>
          <div class="product-price">¥{{ product.price }}</div>
          <div class="product-time">
            <el-icon><Clock /></el-icon>
            {{ formatDate(product.creatTime) }}
          </div>
        </div>

        <div class="product-actions">
          <!-- 已售出商品：只显示查看详情，不能编辑 -->
          <template v-if="product.status === 'sold'">
            <el-button size="small" type="info" disabled>
              <el-icon><View /></el-icon>
              已售出
            </el-button>
            <el-button size="small" type="info" disabled>
              <el-icon><Lock /></el-icon>
              不可编辑
            </el-button>
          </template>
          
          <!-- 其他状态商品：正常操作 -->
          <template v-else>
            <el-button size="small" @click="handleEdit(product)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            
            <!-- 根据商品状态显示不同操作 -->
            <el-button 
              v-if="product.status === 'available'" 
              size="small" 
              type="warning" 
              @click="handleRemoveProduct(product)">
              <el-icon><Remove /></el-icon>
              下架
            </el-button>
            
            <el-button 
              v-if="product.status === 'removed'" 
              size="small" 
              type="success" 
              @click="handleRepublishProduct(product)">
              <el-icon><Plus /></el-icon>
              重新上架
            </el-button>
            
            <el-button size="small" type="danger" @click="handleDelete(product)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </div>
      </el-card>
    </div>

    <!-- 发布/编辑对话框 -->
    <el-dialog
      v-model="showPublishDialog"
      :title="editingProduct ? '编辑商品' : '发布新商品'"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form :model="productForm" :rules="rules" ref="formRef" label-width="90px">
        <el-form-item label="商品名称" prop="productName">
          <el-input v-model="productForm.productName" placeholder="请输入商品名称" />
        </el-form-item>

        <el-form-item label="商品价格" prop="price">
          <el-input-number 
            v-model="productForm.price" 
            :min="0.01"
            :precision="2"
            :step="10"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="新旧程度" prop="oldLevel">
          <el-rate 
            v-model="productForm.oldLevel" 
            :max="10"
            show-score
            score-template="{value} 成新"
          />
        </el-form-item>

        <el-form-item label="商品描述" prop="productDetail">
          <el-input
            v-model="productForm.productDetail"
            type="textarea"
            :rows="4"
            placeholder="请详细描述商品状况、使用情况等"
          />
        </el-form-item>

        <el-form-item label="商品图片" prop="images">
          <div class="image-upload-section">
            <!-- 文件选择器 -->
            <div class="file-input-wrapper">
              <input
                ref="fileInput"
                type="file"
                multiple
                accept="image/*"
                @change="handleFileSelect"
                style="display: none"
              />
              <el-button 
                type="primary" 
                @click="$refs.fileInput.click()"
                :loading="uploading"
              >
                <el-icon><Upload /></el-icon>
                选择图片
              </el-button>
              <span class="upload-tip">支持jpg、png、gif格式，单个文件不超过5MB，<span class="required-tip">至少需要上传1张图片</span></span>
            </div>

            <!-- 图片预览区域 -->
            <div v-if="imageList.length > 0" class="image-preview-grid">
              <div 
                v-for="(image, index) in imageList" 
                :key="index"
                class="image-preview-item"
              >
                <el-image 
                  :src="image.url" 
                  fit="cover"
                  class="preview-image"
                >
                  <template #error>
                    <div class="image-error">
                      <el-icon><PictureFilled /></el-icon>
                      <span>加载失败</span>
                    </div>
                  </template>
                </el-image>
                
                <!-- 删除按钮 -->
                <div class="image-actions">
                  <el-button 
                    type="danger" 
                    size="small" 
                    circle
                    @click="removeImage(index)"
                  >
                    <el-icon><Delete /></el-icon>
                  </el-button>
                </div>
                
                <!-- 上传状态 -->
                <div v-if="image.uploading" class="upload-status">
                  <el-progress 
                    :percentage="image.progress" 
                    :show-text="false"
                    size="small"
                  />
                </div>
              </div>
            </div>

            <!-- 上传进度 -->
            <div v-if="uploading" class="upload-progress">
              <el-progress 
                :percentage="uploadProgress" 
                :status="uploadStatus"
              />
            </div>
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="showPublishDialog = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          {{ editingProduct ? '保存' : '发布' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { productAPI, userAPI } from '@/api'
import {
  Sell,
  Plus,
  PictureFilled,
  Clock,
  Edit,
  Delete,
  Upload,
  Remove,
  List,
  View,
  Lock
} from '@element-plus/icons-vue'

// 数据
const products = ref([])
const loading = ref(false)
const showPublishDialog = ref(false)
const editingProduct = ref(null)
const submitting = ref(false)
const formRef = ref()

// 图片上传相关
const imageList = ref([])
const uploading = ref(false)
const uploadProgress = ref(0)
const uploadStatus = ref('')
const fileInput = ref()

// 表单数据
const productForm = reactive({
  productName: '',
  price: null,
  oldLevel: 5,
  productDetail: '',
  coverList: ''
})

// 表单验证规则
const rules = {
  productName: [
    { required: true, message: '请输入商品名称', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  price: [
    { required: true, message: '请输入价格', trigger: 'blur' }
  ],
  oldLevel: [
    { required: true, message: '请选择新旧程度', trigger: 'change' }
  ],
  productDetail: [
    { required: true, message: '请输入商品描述', trigger: 'blur' },
    { min: 10, message: '描述至少10个字符', trigger: 'blur' }
  ]
}

// 获取我的商品
// 获取当前用户信息
const getCurrentUserInfo = async () => {
  try {
    const response = await userAPI.getUserInfo()
    if (response.code === 0 && response.data) {
      return {
        userId: response.data.user_id,
        username: response.data.username,
        nickName: response.data.nickName,
        displayName: response.data.nickName || response.data.username || `用户${response.data.user_id}`
      }
    }
  } catch (error) {
    // 静默处理错误
  }
  return null
}

const fetchMyProducts = async () => {
  try {
    loading.value = true
    
    // 检查登录状态
    const token = localStorage.getItem('token')
    if (!token) {
      ElMessage.warning('请先登录')
      // 跳转到登录页面
      setTimeout(() => {
        window.location.href = '/userLogin'
      }, 1500)
      return
    }
    
    const response = await productAPI.getMyProducts()
    
    if (response.code === 0) {
      products.value = response.data || []
      
      // 获取当前用户信息并添加到每个商品中
      const userInfo = await getCurrentUserInfo()
      if (userInfo) {
        products.value.forEach(product => {
          product.username = userInfo.username
          product.nickName = userInfo.nickName
          product.userDisplayName = userInfo.displayName
        })
      }
    }
  } catch (error) {
    // 如果是401错误，request.js已经处理了跳转，这里不需要额外处理
    if (error.response?.status !== 401) {
      ElMessage.error('获取商品失败')
    }
  } finally {
    loading.value = false
  }
}

// 编辑商品
const handleEdit = (product) => {
  editingProduct.value = product
  
  // 填充表单数据
  Object.assign(productForm, {
    productName: product.productName,
    price: product.price,
    oldLevel: product.oldLevel,
    productDetail: product.productDetail,
    coverList: product.coverList
  })
  
  // 处理图片数据
  if (product.coverList) {
    try {
      const imageUrls = typeof product.coverList === 'string' 
        ? JSON.parse(product.coverList) 
        : product.coverList
      
      imageList.value = imageUrls.map(url => ({
        url,
        uploaded: true,
        uploading: false,
        progress: 100
      }))
    } catch (error) {
      imageList.value = []
    }
  } else {
    imageList.value = []
  }
  
  showPublishDialog.value = true
}

// 商品状态相关函数
const getStatusType = (status) => {
  const map = {
    'available': 'success',
    'reserved': 'warning',
    'sold': 'info',
    'removed': 'danger'
  }
  
  // 如果没有状态或状态不在映射中，返回默认类型
  if (!status) return 'info'
  return map[status] || 'info'
}

const getStatusText = (status) => {
  const map = {
    'available': '在售',
    'reserved': '已预定',
    'sold': '✅ 已售出',
    'removed': '已下架'
  }
  
  // 如果没有状态或状态不在映射中，返回空字符串
  if (!status) return ''
  return map[status] || ''
}

// 下架商品
const handleRemoveProduct = async (product) => {
  try {
    await ElMessageBox.confirm(
      `确定要下架【${product.productName}】吗？`,
      '下架商品',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await productAPI.updateProduct({
      productId: product.productId,
      status: 'removed'
    })
    ElMessage.success('商品已下架')
    fetchMyProducts()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('下架失败')
    }
  }
}

// 重新上架商品
const handleRepublishProduct = async (product) => {
  try {
    await ElMessageBox.confirm(
      `确定要重新上架【${product.productName}】吗？`,
      '重新上架',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'success'
      }
    )

    await productAPI.updateProduct({
      productId: product.productId,
      status: 'available'
    })
    ElMessage.success('商品已重新上架')
    fetchMyProducts()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('重新上架失败')
    }
  }
}

// 删除商品
const handleDelete = async (product) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除【${product.productName}】吗？`,
      '删除商品',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await productAPI.deleteProduct(product.productId)
    ElMessage.success('删除成功')
    fetchMyProducts()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 查看销售订单
const viewSalesOrders = () => {
  // 跳转到销售订单页面
  window.location.href = '/gear/sales'
}

// 处理发布新商品
const handlePublishNew = () => {
  // 重置所有状态
  resetForm()
  // 显示对话框
  showPublishDialog.value = true
}

// 处理文件选择
const handleFileSelect = async (event) => {
  const files = Array.from(event.target.files)
  if (files.length === 0) return

  // 验证文件
  const validFiles = []
  const invalidFiles = []

  files.forEach(file => {
    if (file.size > 5 * 1024 * 1024) {
      invalidFiles.push(`${file.name} (文件过大，超过5MB)`)
    } else if (!file.type.startsWith('image/')) {
      invalidFiles.push(`${file.name} (不是图片文件)`)
    } else {
      validFiles.push(file)
    }
  })

  if (invalidFiles.length > 0) {
    ElMessage.warning(`以下文件不符合要求：${invalidFiles.join(', ')}`)
  }

  if (validFiles.length === 0) return

  // 上传文件
  await uploadImages(validFiles)
  
  // 清空文件输入
  event.target.value = ''
}

// 上传图片
const uploadImages = async (files) => {
  uploading.value = true
  uploadProgress.value = 0
  uploadStatus.value = ''

  try {
    // 为每个文件创建预览
    files.forEach(file => {
      const imageItem = {
        file,
        url: URL.createObjectURL(file),
        uploading: true,
        progress: 0,
        uploaded: false
      }
      imageList.value.push(imageItem)
    })

    // 上传文件
    const response = await productAPI.uploadImages(files)
    
    if (response.code === 0) {
      const { successUrls, failedFiles } = response.data
      
      // 更新成功上传的图片
      successUrls.forEach((url, index) => {
        const imageItem = imageList.value.find(item => item.uploading && !item.uploaded)
        if (imageItem) {
          imageItem.url = url
          imageItem.uploading = false
          imageItem.uploaded = true
          imageItem.progress = 100
        }
      })

      // 移除失败的文件
      if (failedFiles && failedFiles.length > 0) {
        failedFiles.forEach(failedFile => {
          const index = imageList.value.findIndex(item => 
            item.file && item.file.name === failedFile.split(' ')[0]
          )
          if (index !== -1) {
            imageList.value.splice(index, 1)
          }
        })
        ElMessage.warning(`部分文件上传失败：${failedFiles.join(', ')}`)
      }

      uploadStatus.value = 'success'
      ElMessage.success(`成功上传 ${successUrls.length} 张图片`)
    } else {
      throw new Error(response.message)
    }
  } catch (error) {
    uploadStatus.value = 'exception'
    ElMessage.error('图片上传失败：' + error.message)
    
    // 移除上传失败的图片
    imageList.value = imageList.value.filter(item => !item.uploading)
  } finally {
    uploading.value = false
    uploadProgress.value = 100
  }
}

// 删除图片
const removeImage = async (index) => {
  const imageItem = imageList.value[index]
  
  try {
    // 如果图片已上传到服务器，先删除服务器上的图片
    if (imageItem.uploaded && imageItem.url.startsWith('http')) {
      await productAPI.deleteImage(imageItem.url)
    }
    
    // 移除本地预览
    imageList.value.splice(index, 1)
    ElMessage.success('图片已删除')
  } catch (error) {
    ElMessage.error('删除图片失败')
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    
    // 检查图片数量
    const uploadedImages = imageList.value.filter(item => item.uploaded)
    if (uploadedImages.length === 0) {
      ElMessage.error('请至少上传一张商品图片')
      return
    }
    
    submitting.value = true

    // 准备提交数据
    const data = {
      productName: productForm.productName,
      productDetail: productForm.productDetail,
      oldLevel: productForm.oldLevel,
      price: productForm.price,
      files: imageList.value.filter(item => item.file).map(item => item.file)
    }

    if (editingProduct.value) {
      // 更新商品（暂时使用原有接口）
      data.productId = editingProduct.value.productId
      data.coverList = JSON.stringify(imageList.value.filter(item => item.uploaded).map(item => item.url))
      await productAPI.updateProduct(data)
      ElMessage.success('更新成功')
    } else {
      // 发布新商品
      if (data.files.length > 0) {
        await productAPI.addProductWithFiles(data)
      } else {
        await productAPI.addProduct({
          ...data,
          coverList: JSON.stringify(imageList.value.filter(item => item.uploaded).map(item => item.url))
        })
      }
      ElMessage.success('发布成功')
    }

    showPublishDialog.value = false
    resetForm()
    fetchMyProducts()
  } catch (error) {
    if (error !== false) {
      ElMessage.error('操作失败')
    }
  } finally {
    submitting.value = false
  }
}

// 重置表单
const resetForm = () => {
  editingProduct.value = null
  Object.assign(productForm, {
    productName: '',
    price: null,
    oldLevel: 5,
    productDetail: '',
    coverList: ''
  })
  
  // 清空图片列表
  imageList.value = []
  uploading.value = false
  uploadProgress.value = 0
  uploadStatus.value = ''
  
  formRef.value?.clearValidate()
}

// 工具函数
const getImageUrl = (coverList) => {
  if (!coverList) return ''
  try {
    const list = typeof coverList === 'string' ? JSON.parse(coverList) : coverList
    return Array.isArray(list) ? list[0] : list
  } catch {
    return coverList
  }
}

const getOldLevelText = (level) => {
  const map = { 
    1: '1成新', 
    2: '2成新', 
    3: '3成新', 
    4: '4成新', 
    5: '5成新', 
    6: '6成新', 
    7: '7成新', 
    8: '8成新', 
    9: '9成新', 
    10: '全新' 
  }
  
  // 如果没有新旧程度或不在映射中，返回空字符串
  if (!level || level < 1 || level > 10) return ''
  return map[level] || ''
}

const getOldLevelType = (level) => {
  // 如果没有新旧程度或不在有效范围内，返回默认类型
  if (!level || level < 1 || level > 10) return 'info'
  
  if (level >= 9) return 'success'
  if (level >= 7) return 'info'
  if (level >= 5) return 'warning'
  return 'danger'
}

const formatDate = (dateString) => {
  if (!dateString) return ''
  return new Date(dateString).toLocaleDateString('zh-CN')
}

onMounted(() => {
  fetchMyProducts()
})
</script>

<style scoped lang="scss">
.my-selling-page {
  min-height: 100vh;
  background: #f5f7fa;
  padding: 20px;
}

.page-header {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
  color: white;
  padding: 30px;
  border-radius: 12px;
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 4px 12px rgba(240, 147, 251, 0.3);

  .header-left {
    display: flex;
    align-items: center;
    gap: 15px;
  }

  .header-icon {
    font-size: 36px;
  }

  .header-title {
    font-size: 28px;
    margin: 0;
    font-weight: 600;
  }

  .header-subtitle {
    margin: 5px 0 0 0;
    font-size: 14px;
    opacity: 0.9;
  }
}

.loading-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;

  .loading-card {
    height: 300px;
  }
}

.empty-state {
  background: white;
  border-radius: 12px;
  padding: 80px 20px;
  text-align: center;
}

.products-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;

  .product-card {
    border-radius: 12px;
    overflow: hidden;
    transition: all 0.3s;

    &:hover {
      transform: translateY(-5px);
      box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
    }
  }
}

.product-image {
  height: 200px;
  overflow: hidden;

  .image-error {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #f5f7fa;
    color: #909399;
    font-size: 48px;
  }
}

.product-info {
  padding: 15px;

  .product-name {
    font-size: 16px;
    margin: 0 0 10px 0;
    height: 44px;
    overflow: hidden;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
  }

  .product-meta {
    margin-bottom: 10px;
  }

  .product-price {
    font-size: 22px;
    color: #f56c6c;
    font-weight: 700;
    margin-bottom: 10px;
  }

  .product-time {
    font-size: 12px;
    color: #909399;
    display: flex;
    align-items: center;
    gap: 5px;
  }
}

.product-actions {
  padding: 0 15px 15px;
  display: flex;
  gap: 10px;

  .el-button {
    flex: 1;
  }
}

.image-preview {
  margin-top: 10px;
  width: 120px;
  height: 120px;
  border-radius: 8px;
  overflow: hidden;
}

/* 图片上传区域样式 */
.image-upload-section {
  width: 100%;
}

.file-input-wrapper {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 16px;
}

.upload-tip {
  color: #909399;
  font-size: 12px;
}

.required-tip {
  color: #f56c6c;
  font-weight: 500;
}

.image-preview-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
  gap: 12px;
  margin-top: 16px;
}

.image-preview-item {
  position: relative;
  border-radius: 8px;
  overflow: hidden;
  background: #f5f7fa;
  border: 1px solid #e4e7ed;
}

.preview-image {
  width: 100%;
  height: 120px;
  display: block;
}

.image-error {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 120px;
  color: #c0c4cc;
  font-size: 12px;
}

.image-error .el-icon {
  font-size: 24px;
  margin-bottom: 4px;
}

.image-actions {
  position: absolute;
  top: 4px;
  right: 4px;
  opacity: 0;
  transition: opacity 0.3s;
}

.image-preview-item:hover .image-actions {
  opacity: 1;
}

.upload-status {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.6);
  padding: 4px 8px;
}

.upload-progress {
  margin-top: 16px;
}

/* 已售出商品特殊样式 */
.sold-tag {
  background: linear-gradient(135deg, #67c23a, #5cb85c) !important;
  color: white !important;
  font-weight: 600 !important;
  border: 2px solid #67c23a !important;
  box-shadow: 0 2px 8px rgba(103, 194, 58, 0.3) !important;
}

/* 已售出商品卡片样式 */
.product-card:has(.sold-tag) {
  opacity: 0.8;
  background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
  border: 2px solid #67c23a;
  position: relative;
}

.product-card:has(.sold-tag)::before {
  content: '已售出';
  position: absolute;
  top: 10px;
  right: 10px;
  background: linear-gradient(135deg, #67c23a, #5cb85c);
  color: white;
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 600;
  z-index: 2;
  box-shadow: 0 2px 8px rgba(103, 194, 58, 0.3);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .image-preview-grid {
    grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
    gap: 8px;
  }
  
  .preview-image {
    height: 100px;
  }
  
  .image-error {
    height: 100px;
  }
}
</style>
